<template>
  <div class="mainor">
    <div @click="mainor_co = false">
      <el-form
        :inline="true"
        :rules="rules"
        :model="monitorForm"
        class="demo-form-inline"
        ref="userListFrom"
        label-width="60px"
      >
        <div class="main_spac1 paddingBottom5">
          <div class="main_white padding10 paddingBottom0">
            <div class="main_crumbs boxdq">
              <div class="main_crumbs_l">
                <a href="javascript:;" @click="$router.back(-1)">
                  <i class="el-icon-arrow-down"></i>返回
                </a>
                <em>|</em>
                <span>创建盘点单</span>
              </div>
            </div>
            <div class="marginBottom5 marginTop5">
              <el-form-item
                label="备注"
                prop="form.remark"
                class="marginRight0 marginTop10 remark_in"
              >
                <el-input
                  v-model.trim="monitorForm.form.remark"
                  placeholder="备注"
                  clearable
                  @change="isEdit = true"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
        <!-- 商品名称 -->
        <div class="main_spac1" style="padding-top: 5px">
          <div class="main_white padding10">
            <div class="mainor_sp boxdq" style="">
              <div class="box">
                <ul class="box">
                  <li class="box">
                    <span> <em>*</em>商品名称： </span>
                    <el-autocomplete
                      v-model="formsp.value"
                      ref="searchSelect"
                      class="wid240 main_comm"
                      @clear="$refs.searchSelect.$children[0].blur()"
                      :fetch-suggestions="
                        (queryString, cb) => {
                          querySearchAsync(queryString, cb);
                        }
                      "
                      placeholder="商品名称/别名/编码/助记码"
                      clearable
                      :highlight-first-item="true"
                      value-key="name"
                      @select="
                        (item) => {
                          handleSelect(item);
                        }
                      "
                    >
                      <template slot-scope="{ item }">
                        <!-- <div class="main_name">
                          {{ item.goods.name }}【{{ item.spu_unit.title }}】
                        </div>
                        <span
                          class="main_addr"
                          >{{ item.goods_spu_code }}</span
                        > -->
                        <div class="main_name">
                          <span>
                            {{ item.goods.name }}【{{
                              item.spu_name ? item.spu_name.title : ""
                            }}】
                          </span>
                          <span class="code">{{ item.goods_spu_code }}</span>
                        </div>
                      </template>
                    </el-autocomplete>
                  </li>
                  <li class="box">
                    <span> <em>*</em>数量： </span>
                    <el-input
                      v-model.trim="formsp.num"
                      ref="focusw2"
                      placeholder="数量"
                      clearable
                      class="wid140"
                      @keyup.enter.native="mainor_sp"
                    ></el-input>
                  </li>
                </ul>
                <div class="marginBottom10">
                  <el-button type="primary" @click="mainor_qr"
                    >确认(回车)</el-button
                  >
                  <el-button
                    class="reset marginLeft5"
                    type="info"
                    @click="reset"
                    >重置</el-button
                  >
                </div>
              </div>
              <div>
                <el-button @click.stop="exportb" class="mainor_copy">
                  <div class="box">
                    自动导入漏盘商品
                    <div
                      class="mainsu_te marginLeft5"
                      style="position: relative; margin-top: -4px"
                    >
                      <el-tooltip class="item" effect="dark" placement="top">
                        <div slot="content">
                          注释：系统会自动导入没有添加的，库存不为0的所有商品到列表，且实际库存默认用0填充！
                        </div>
                        <svg
                          aria-hidden="true"
                          class="navbar_svg"
                          width="16"
                          height="16"
                        >
                          <use xlink:href="#icon-summary_question" />
                        </svg>
                      </el-tooltip>
                    </div>
                  </div>
                </el-button>
                <el-button @click.stop="mainor_copy" class="mainor_copy"
                  >复制盘点单</el-button
                >
              </div>
            </div>
            <div
              class="main_table main_taf marginTop0"
              style="min-height: 330px"
            >
              <el-table
                ref="multipleTable"
                :data="monitorForm.list"
                element-loading-text="加载中"
                fit
                border
                highlight-current-row
                :header-cell-class-name="this.$verticaline"
              >
                <el-table-column label="序号">
                  <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column
                  label="商品名称"
                  prop="name"
                  width="200"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope"
                    >{{ scope.row.name }}【{{ scope.row.spu_name }}】</template
                  >
                </el-table-column>
                <el-table-column
                  label="单位"
                  prop="unit"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  label="库存价"
                  prop="price"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  label="系统库存"
                  prop="inventory_num"
                  width="120"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  label="实际库存"
                  width="200"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.num'"
                      :rules="rules.num"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.num"
                        :ref="'num' + scope.row.goods_spu_id"
                        placeholder="实际库存"
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  width="350"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model.trim="scope.row.remark"
                      placeholder="备注"
                      class="wid240"
                    ></el-input>
                    <el-link type="danger" @click="scdelete(scope.$index)"
                      >删除</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="newConBox_p200 paddingBottom10" id="newConBox">
              <div class="newConBox_h32">
                <div
                  :class="[
                    'mainor_pr boxdq newConBox ',
                    { on: searchBarFixed },
                  ]"
                >
                  <div class="mainor_prl">
                    <el-button
                      type="primary"
                      @click="preservation"
                      v-repeatClick
                      >保存</el-button
                    >
                    <el-button @click="$router.back(-1), (isEdit = false)"
                      >取消</el-button
                    >
                  </div>
                  <div class="mainor_prr">
                    <span>合计金额：¥{{ total }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 复制盘点单 -->
    <div :class="[{ on: mainor_co }, ' mainor_co']">
      <div class="mainor_cob">
        <div class="mainor_cob_c" @click="mainor_co = false">
          <i class="el-icon-close"></i>
        </div>
        <div class="mainor_cob_s">
          <el-input
            placeholder="盘点单号"
            v-model="input"
            class="input-with-select main_search"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="mainor_cob_s"
            ></el-button>
          </el-input>
          <p>只展示符合条件的前10个盘点单</p>
        </div>
        <div class="main_table">
          <div class="main_table_p">
            <el-table
              ref="multipleTable"
              :data="list_co"
              element-loading-text="加载中"
              height="90%"
              fit
              highlight-current-row
            >
              <el-table-column label="序号" width="60">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="盘点单号" prop="order_sn" width="180" />
              <el-table-column label="配送时间" prop="userNickname" width="100">
                <template slot-scope="scope">{{
                  parseTime(scope.row.created_at, "{y}-{m}-{d}")
                }}</template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="100"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="copy(scope.row.id)"
                    v-repeatClick
                    >复制</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  list: {
    name: "",
    goods_id: "",
    goods_spu_id: "",
    spu_name: "",
    unit: "",
    inventory_num: "",
    price: "",
    num: "",
    remark: "",
    show: false,
  },
  form: {
    remark: "",
  },
  formsp: {
    name: [],
    girard: null,
    num: "",
    value: "",
  },
};

import {
  inventorySheet_add,
  inventorySheet_copyList,
  inventorySheet_allGoodsSpuInventory,
  inventorySheet_checkGoods,
  inventorySheet_getInventorySheetList,
} from "@/api/warehouse/warehouseCheck";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseCheck_add";
import { goods_getGoodsSpu } from "@/api/currency";
import { parseTime, jsonStringifyBack } from "@/utils/index";

export default {
  computed: {
    total() {
      let sz = 0;
      this.monitorForm.list.forEach((e) => {
        sz += parseFloat(e.num * e.price);
      });
      return this.$toFixed(sz);
    },
  },
  components: {},
  data() {
    return {
      // 时间
      parseTime,
      // 验证
      rules,
      // 列表数据
      monitorForm: {
        form: {
          remark: "",
        },
        list: [],
      },
      // 复制盘点单
      mainor_co: false,
      input: "",
      list_co: [],
      // 商品搜索
      formsp: {
        name: [],
        girard: null,
        num: "",
        value: "",
      },
      inventory_num: "",
      price: "",
      show: true,
      // 监听滚动
      searchBarFixed: false,
      isEdit: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {},
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 自动导入漏盘商品
    exportb() {
      let list = JSON.parse(JSON.stringify(this.monitorForm.list));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { goods_spu_ids: JSON.stringify(list.map((e) => e.goods_spu_id)) }
      );
      this.$confirm(
        "系统会自动导入没有添加的，库存不为0的所有商品到列表，且实际库存默认用0填充，确定吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          inventorySheet_allGoodsSpuInventory(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "导入成功",
                type: "success",
              });
              this.standard(res.data.list, true);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 复制盘点单
    mainor_copy() {
      this.mainor_co = true;
      this.inventorySheet_copyList();
    },
    // 复制盘点单-搜索
    mainor_cob_s() {
      this.inventorySheet_copyList();
    },
    // 复制盘点单-复制
    copy(id) {
      this.mainor_co = false;
      this.inventorySheet_getInventorySheetList(id);
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          res.data.goods.map((e) => {
            e.name = e.goods.name + "【" + e.spu_unit.title + "】";
          });
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.formsp.name = item;
      this.formsp.girard = item.id;
      this.inventorySheet_checkGoods();
    },
    inventorySheet_checkGoods() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                goods_id: formsp.name.goods_id,
                goods_spu_id: formsp.girard,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          goods_id: formsp.name.goods_id,
          goods_spu_id: formsp.girard,
        }
      );
      inventorySheet_checkGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.inventory_num = res.data.num;
          this.price = res.data.price;
          setTimeout(() => {
            this.$refs.focusw2.focus();
          }, 100);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      this.isEdit = true;
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.name.name) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let monitorForm_list = JSON.parse(
          JSON.stringify(this.monitorForm.list)
        );
        let ind = 0;
        if (monitorForm_list.length != 0) {
          monitorForm_list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.handle(formsp);
          } else {
            setTimeout(() => {
              this.$refs["num" + ind].focus();
              this.reset();
              ind = 0;
            }, 100);
          }
        } else {
          this.handle(formsp);
        }
      }
    },
    handle(formsp) {
      let list = JSON.parse(JSON.stringify(shuju.list));
      list.name = formsp.name.goods.name;
      list.goods_id = formsp.name.goods_id;
      list.goods_spu_id = formsp.name.id;
      list.spu_name = formsp.name.spu_name ? formsp.name.spu_name.title : "";
      list.unit = formsp.name.spu_unit ? formsp.name.spu_unit.title : "";
      list.price = this.price;
      list.inventory_num = this.inventory_num;
      list.num = formsp.num;
      list.remark = formsp.name.remark;
      this.monitorForm.list.push(list);
      this.reset();
      setTimeout(() => {
        this.$refs.searchSelect.focus();
      }, 100);
    },
    reset() {
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    // 删除
    scdelete(index) {
      if (parseFloat(this.monitorForm.list[index].num) >= 0) {
        this.$confirm("确定要删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.monitorForm.list.splice(index, 1);
          })
          .catch(() => {});
      } else {
        this.monitorForm.list.splice(index, 1);
      }
    },
    // 保存
    preservation() {
      this.isEdit = true;
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (this.monitorForm.list.length == 0) {
            this.$message.error("请至少添加一个商品");
            return;
          }

          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            this.order_data().form,
            { list: JSON.stringify(this.order_data().list, jsonStringifyBack) }
          );

          inventorySheet_add(data).then((res) => {
            this.isEdit = false;
            if (res.errcode == 0) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },

    order_data() {
      // let form = JSON.parse(JSON.stringify(this.monitorForm.form));
      // let sz = JSON.parse(JSON.stringify(this.monitorForm.list));
      let form = Object.create(this.monitorForm.form);
      let sz = Object.create(this.monitorForm.list);
      let list = sz.map((e) => {
        let { name, spu_name, unit, show, inventory_num, ...sz } = e;
        return { ...sz };
      });

      return { form, list };
    },
    // 复制盘点单
    inventorySheet_copyList() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                uid: this.monitorForm.form.uid,
                order_sn: this.input,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { uid: this.monitorForm.form.uid, order_sn: this.input }
      );
      inventorySheet_copyList(data).then((res) => {
        if (res.errcode == 0) {
          this.list_co = res.data.list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    inventorySheet_getInventorySheetList(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      inventorySheet_getInventorySheetList(data).then((res) => {
        if (res.errcode == 0) {
          this.standard(res.data.list);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    standard(data, type) {
      let arry = [];
      data.map((e) => {
        arry.push({
          name: e.goods.name,
          goods_id: e.goods_id,
          goods_spu_id: e.goods_spu_id,
          spu_name: e.goods_spu.spu_name ? e.goods_spu.spu_name.title : "",
          unit: e.goods_spu.spu_unit ? e.goods_spu.spu_unit.title : "",
          inventory_num: e.num,
          price: e.price,
          num: "0.00",
          remark: e.remark,
          show: true,
        });
      });
      if (type) {
        arry.map((e) => {
          this.monitorForm.list.push(e);
        });
      } else {
        this.monitorForm.list = arry;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.main_name {
  top: 5px;
  position: relative;
}
.main_addr {
  top: -5px;
  position: relative;
}
.mainor_copy {
  position: relative;
  top: -4px;
}
.mainsu_te .navbar_svg use {
  fill: $menuActiveText;
}
.mainor {
  /deep/.el-button--default {
    border-color: $menuActiveText;
    color: $menuActiveText;
  }
  /deep/.el-form {
    margin-top: 10px;
    /deep/.el-form-item--mini.el-form-item,
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }
  }
  .remark_in {
    width: 100%;
    /deep/.el-form-item__content {
      width: 80%;
      .el-input {
        width: 66.9%;
      }
    }
  }
  .mainor_co {
    position: fixed;
    width: 460px;
    height: 100%;
    background: $white;
    box-shadow: 0 6px 10px rgba(0, 21, 41, 0.08);
    top: 0;
    right: 0;
    z-index: 9999;
    transition: all 0.5s;
    transform: translate3d(100%, 0, 0);
    /deep/.el-button--default {
      border: 0;
    }
    &.on {
      transform: translate3d(0, 0, 0);
    }
    .mainor_cob_c {
      position: absolute;
      top: 15px;
      right: 15px;
      i {
        font-size: 22px;
        font-weight: bold;
        color: $colour_6;
      }
      &:hover {
        cursor: pointer;
      }
    }
    .mainor_cob_s {
      margin-top: 50px;
      margin-left: 10px;
      margin-right: 10px;
      p {
        font-size: $font_12;
        color: $colour_red;
        margin-top: 10px;
      }
      /deep/.el-input-group {
        width: 100%;
      }
    }
    .main_table {
      margin-left: 0;
      position: fixed;
      top: 0;
      height: calc(100% - 120px);
      width: 100%;
      margin-top: 120px;
      /deep/.el-table__body-wrapper {
        border-left: 0;
        table {
          border-left: 1px solid #ebeef5;
        }
      }
      /deep/.el-table__fixed-body-wrapper {
        border-right: 0;
        table {
          border-right: 1px solid #ebeef5;
        }
      }
      .main_table_p {
        margin-left: 10px;
        margin-right: 10px;
        height: 100%;
      }
      /deep/.el-table th .cell {
        font-size: $font_14;
      }
    }
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .newConBox.on {
    width: calc(100% - 230px);
    padding-left: 0;
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
    /deep/.el-button--default {
      border-color: $subActive;
      color: $menuText;
      &:hover {
        border-color: $menuActiveText;
        color: $menuActiveText;
      }
    }
    .mainor_prr {
      font-size: $font_16;
      color: $colour_18;
      span {
        color: #fe3b3b;
        margin-left: 10px;
      }
    }
  }
  .main_table {
    /deep/.el-table--small td {
      padding: 10px 0;
    }
  }
  .main_taf {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
}
.main_name {
  display: flex;
  flex-direction: column;
  line-height: initial;
  padding: 8px 0;
  .code {
    color: #999;
  }
}
</style>
